////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//   Software       :                                                         //
//   Layer          : SRC                                                     //
//   Package        :                                                         //
//   Component      :                                                         //
//                                                                            //
//   File           : FormMain.cpp                                            //
//   Author         : RSO ( Rafael Sotomayor Brûlé )                          //
//   EMail          : rsotomayor@savtec.cl                                    //
//   Type           : C++ Source                                              //
//   Usage          :                                                         //
//   Purpose        : Definición de ATD  globales                             //
//                                                                            //
//                                                                            //
//   who when        what                                                     //
//   ~~~ ~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//   RSO 09-10-2010  Creation                                                 //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

#include "mylib/errlog.h"
#include "mylib/utilconf.h"
#include "xsendkey.h"
#include "formmain.h"
#include "formconfig.h"
#include "myglobal.h"
#include "myconfig.h"
#include "cpost.h" 

#include "formmain.h"
#include "formconfig.h"
#include "myserver.h"


#define TIMEOUT_BACKLIGHT (60*10)

extern FormMain    *myFormMain_g;
extern FormConfig  *myFormConfig_g;

extern MyColor     mygdkcolor_g ;
extern MyGlobal    *global_g;
extern MyConfig    *config_g;

FormMain* FormMain::pFormMain_a=NULL;
GtkBuilder   *builder_g;

FormMain::FormMain() {
  pFormMain_a = this ;
  ptimer_a=0;
  myWidget_a = g_slice_new( MyWidget );
  MyForm::init();

  tEntryActivity_a = time(NULL);
  flagUpdate_a = false;
  modoBackLight_a = true ;

}

FormMain::~FormMain() {
  g_slice_free( MyWidget, myWidget_a );	
}

gint FormMain::RePaint(gpointer data) {
  gchar txtbuffer[1024];
  string mytext = "" ;

  time_t  tsnow;
  tsnow = time(NULL) + config_g->gmtoffset_a*60*60;
  struct tm *tmPtr;
  tmPtr = localtime(&tsnow);
  strftime(txtbuffer, 32, "%a %d-%m-%Y %H:%M:%S", tmPtr );

  mytext = txtbuffer ;
  gtk_label_set_text ( (GtkLabel *) pFormMain_a->myWidget_a->labelclock ,mytext.data());
  

  return TRUE;

}

int FormMain::initializeBuilder(string file_p) {

  if ( file_p != "" ) {
    builder_g = gtk_builder_new ();
    gtk_builder_add_from_file (builder_g, file_p.data(), NULL);
  } 

  window_a                  = GTK_WIDGET (gtk_builder_get_object (builder_g, "windowmain"));
  myWidget_a->labelclock    = GTK_WIDGET (gtk_builder_get_object (builder_g,"labelclock"));
  myWidget_a->buttonconfig  = GTK_WIDGET (gtk_builder_get_object (builder_g,"buttonconfig"));
  
  gtk_builder_connect_signals (builder_g, NULL);  

  PangoFontDescription    *fd = NULL;
  fd = pango_font_description_from_string (FONT_MAIN_BIG_BOLD);

  gtk_widget_modify_fg (myWidget_a->labelclock, GTK_STATE_NORMAL, &mygdkcolor_a.color_white); 
  gtk_widget_modify_font (myWidget_a->labelclock, fd);  


#if defined(__arm__)  
  gtk_window_set_decorated((GtkWindow* ) window_a, FALSE);  
#endif
  
  string filename;

  filename  = config_g->pathImage_a ;
  filename += "s100_bg.png";   
  setBackGround(filename);
 
  myFormConfig_a       = new FormConfig();

  return 0;
}


void FormMain::setCallBack() {
  ptimer_a = gtk_timeout_add(1000,this->RePaint,window_a);
  g_signal_connect(GTK_OBJECT (window_a), "destroy", GTK_SIGNAL_FUNC (on_window_destroy), NULL);  
  g_signal_connect(GTK_OBJECT (myWidget_a->buttonconfig), "clicked", GTK_SIGNAL_FUNC (on_window_config), NULL);  

}


void FormMain::on_window_destroy(GtkWidget *widget_p,gpointer data_p) {
  int counter;
  global_g->isOn_a = 0 ;
  counter = 0 ;
  while ( counter++ < 1 ) {
    
    errLog::LOGERR((errLog::INFO,(char *) "WAITING TO QUIT  [%d] \n",counter));
    sleep(1);
  }
  gtk_main_quit ();
}


void FormMain::on_keypad_clicked (GtkWidget *widget,gpointer data_p) {

  if ( pFormMain_a->modoBackLight_a == false  ) {
    pFormMain_a->modoBackLight_a = true;
    errLog::LOGERR((errLog::INFO,"BACKLIGHT ON\n"));
//    system("source /ts.subr;backlite_on");
  }

  pFormMain_a->tEntryActivity_a = time(NULL);
  char buffer[32];
  int dato=GPOINTER_TO_INT (data_p);

 
  if ( dato == '#' ) {
    // Ingresa comando
  } else if ( dato == 'a' ) {
      // IDLE
  } else if ( dato == 'c' || dato == 'd' ) {
    // No hace nada
  } else if ( dato == 'b' ) {
    SendKey((char *)"Back+");
  } else {
    SendKey(buffer);
  }


}


void FormMain::on_window_config(GtkWidget *widget_p,gpointer data_p) {
 errLog::LOGERR((errLog::TRACE,"on_window_config\n"));
  pFormMain_a->showConfig();
}

void FormMain::showConfig() {
 errLog::LOGERR((errLog::INFO,"showConfig \n"));
 if ( myFormConfig_a->flagInit_a == false ) {
    // En caso de que la ventana se haya "destroy"
    errLog::LOGERR((errLog::INFO,"showConfig Initialize\n"));
    myFormConfig_a->initialize("");
    myFormConfig_a->setWindowParent(window_a);
    myFormConfig_a->setCallBack();
  }

  global_g->windowActiva_a = MyGlobal::WINDOW_CONFIG;
  myFormConfig_a->show();
  gtk_widget_hide(window_a);
}

void FormMain::setLabelPrincipal(string mensaje_p) {


}


void FormMain::initServicios() {
  pthread_t threadID;              // Thread ID from pthread_create()

  // Create client thread
  if (pthread_create(&threadID, NULL, ThreadInitServicios, NULL ) != 0) {
    errLog::LOGERR((errLog::SEVERE,"Error lanzando Thread\n"));
  }

}


void *FormMain::ThreadInitServicios(void *threadArgs_p) {

  errLog::LOGERR((errLog::TRACE,"Begin Thread InitServicios\n"));

  MyServer myserver_g(13500);
  myserver_g.startTareas();


  CPost mypost;
  mypost.testServer();

  pFormMain_a->setEstadoServicios();
  
  time_t timeoutCheckServer;
  timeoutCheckServer=time(NULL);

  int contador=0;
  
  while ( global_g->isOn_a ) {

    if ( (time(NULL) - pFormMain_a->tEntryActivity_a ) > TIMEOUT_BACKLIGHT) {
      pFormMain_a->tEntryActivity_a = time(NULL);
      pFormMain_a->modoBackLight_a = false ;
      errLog::LOGERR((errLog::INFO,"BACKLIGHT OFF\n"));
//      system("source /ts.subr;backlite_off");
    }

    if ( ( time(NULL) - timeoutCheckServer ) >=  TIMEOUT_CHECK_SERVER ) {
      timeoutCheckServer=time(NULL);
      mypost.testServer();
    }

    errLog::LOGERR((errLog::DEBUG,"Thread Servicios %d\n",contador++));

    sleep(1);
  }

  return (NULL);
}

void FormMain::setEstadoServicios() {

  gdk_threads_enter();               

  gdk_threads_leave();


}

